import datetime
import json
import time
import sys
import traceback

from PyQt5.QtGui import QIntValidator
from PyQt5.QtWidgets import (QMainWindow, QApplication, QInputDialog, QLineEdit, QComboBox, QMessageBox
                             )
from PyQt5.QtCore import Qt, QTimer, QEventLoop, QCoreApplication

from UI.UI_MainWindow import Ui_MainWindow
from UI.styles import TOOL_BUTTON_CONNECTED_STYLE, TOOL_BUTTON_DISCONNECTED_STYLE, TOOL_BUTTON_UPDATE_STYLE
from command_process import DTUManager

LOADING = "加载中..."

dtu = DTUManager()
PORTS = DTUManager.detect_serial_ports()
_TRANSLATE = QCoreApplication.translate

OTA_STATUS = {
    0: "升级成功",
    1: "无需升级/连接失败",
    2: "链接错误",
    3: "服务器断开",
    4: "接收报文错误",
    5: "版本信息错误"
}


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.init_ui()
        self.set_int_validator()
        # 初始化一个定时器用于模拟数据加载延迟
        self.data_load_timer = QTimer(self)
        self.data_load_timer.setSingleShot(True)

        # 创建一个定时器用于定期更新状态
        self.status_update_timer = QTimer(self)
        self.status_update_timer.timeout.connect(self.fill_statabs)
        # 设置更新间隔为 60 秒
        self.status_update_timer.setInterval(60000)

        self.refresh_function_dict = {
            "dtu_read": self.get_dtu_data,
            "socket_read": self.get_socket_data,
            "socket1_read": self.get_socket1_data,
            "sim_read": self.get_sim_data,
            "sys_read": self.get_sys_data
        }

    def init_ui(self):
        # 连接按钮信号到槽函数
        self.pushButton.clicked.connect(self.clear_action)  # 清除按钮
        self.pushButton_3.clicked.connect(self.restart_action)  # 重启按钮
        self.pushButton_2.clicked.connect(self.get_sleep_time)  # 休眠按钮
        self.pushButton_4.clicked.connect(self.shutdown_action)  # 关机按钮
        self.pushButton_5.clicked.connect(self.save_dtu_data)  # dtu配置应用按钮
        self.pushButton_6.clicked.connect(self.save_socket_data)  # socket配置应用按钮
        self.pushButton_7.clicked.connect(self.clear_text_browser)  # 清空日志按钮
        self.pushButton_9.clicked.connect(self.save_socket1_data)  # socket1配置应用按钮
        self.pushButton_16.clicked.connect(self.connect_device)  # 连接设备按钮
        self.pushButton_10.clicked.connect(self.custom_instruction)  # 自定义指令发送请求按钮
        self.pushButton_11.clicked.connect(self.fill_dtutabs)  # dtu配置刷新按钮
        self.pushButton_12.clicked.connect(self.fill_sockets)  # socket配置刷新按钮
        self.pushButton_13.clicked.connect(self.fill_socket1tabs)  # socket1配置刷新按钮
        self.pushButton_14.clicked.connect(self.fill_systabs)  # sys配置刷新按钮
        self.pushButton_15.clicked.connect(self.fill_simtabs)  # sim配置刷新按钮
        self.pushButton_17.clicked.connect(self.upgrade)  # 升级按钮
        self.comboBox_4.currentIndexChanged.connect(self.on_combo_box_changed)
        self.lineEdit_18.textChanged.connect(self.on_text_changed)

        # 连接页签切换信号到填充数据的槽函数
        self.tabWidget.currentChanged.connect(self.on_tab_changed)

    def start_status_updates(self):
        """启动状态更新定时器"""
        self.fill_statabs()
        self.status_update_timer.start()

    def on_tab_changed(self, index):
        """当页签改变时，根据当前页签索引填充数据"""
        if index == 0:  # 自定义指令标签页
            pass

    def custom_instruction(self):
        """自定义指令发送请求"""
        print("自定义指令发送请求")
        cmd = self.plainTextEdit.toPlainText()
        if self.radioButton_3.isChecked():
            cmd += "\r\n"
        data = dtu.get_custom_data(cmd)

        self.plainTextEdit_2.setPlainText(_TRANSLATE("MainWindow", data))
        if "ok" in data:
            self.set_tool_button_connected_style()

    def fill_statabs(self):
        """填充状态标签页"""
        print("填充状态标签页")

        self.toolButton.setStyleSheet(TOOL_BUTTON_UPDATE_STYLE)
        self.toolButton.setText(_TRANSLATE("MainWindow", "数据更新中"))
        # 强制更新界面
        QApplication.processEvents()
        data = self.get_data('sta_read')
        print(data)

        self.lineEdit_11.setText(data.get("network_status", "- -"))
        self.lineEdit_12.setText(data.get("socket_status", "- -"))
        self.lineEdit_13.setText(data.get("socket1_status", "- -"))
        self.lineEdit_14.setText(data.get("csq", "- -"))
        self.lineEdit_15.setText(data.get("rssi", "- -"))
        self.lineEdit_16.setText(data.get("snr", "- -"))
        error_info = data.get("error_info")
        if error_info == dtu.SUCCESS:
            self.set_tool_button_connected_style()
            self.load_data()
        elif not error_info:
            error_info = "连接未响应,请检查串口"
            self.toolButton.setStyleSheet(TOOL_BUTTON_DISCONNECTED_STYLE)
            self.toolButton.setText(_TRANSLATE("MainWindow", "离线"))
            self.display_message(error_info)
        else:
            self.toolButton.setStyleSheet(TOOL_BUTTON_DISCONNECTED_STYLE)
            self.toolButton.setText(_TRANSLATE("MainWindow", "离线"))
            self.display_message(error_info)

    def set_tool_button_connected_style(self):
        self.toolButton.setStyleSheet(TOOL_BUTTON_CONNECTED_STYLE)
        self.toolButton.setText(_TRANSLATE("MainWindow", "在线"))
        self.pushButton_16.setText(_TRANSLATE("MainWindow", "刷新状态"))

    def connect_device(self):

        # 启动状态更新定时器
        self.start_status_updates()

    def fill_dtutabs(self):
        """填充DTU配置标签页"""
        print("填充DTU配置标签页")
        data = {
            "work_mode": "单通道",
            "apn": LOADING,
            "username": LOADING,
            "password": LOADING,
            "run_mode": "正常",
            "baud_rate": "0",
            "timeout": "0",
            "rs485_mode": "启用"
        }

        self.set_line_edit_text(self.comboBox, data["work_mode"])
        self.set_line_edit_text(self.lineEdit, data["apn"])
        self.set_line_edit_text(self.lineEdit_2, data["username"])
        self.set_line_edit_text(self.lineEdit_3, data["password"])
        self.set_line_edit_text(self.lineEdit_4, data["baud_rate"])
        self.set_line_edit_text(self.lineEdit_5, data["timeout"])
        self.radioButton.setChecked(data["rs485_mode"] == "启用")
        # 断开定时器已有的连接
        try:
            self.data_load_timer.timeout.disconnect()
        except TypeError:
            pass
        # 启动定时器模拟数据加载延迟
        self.data_load_timer.timeout.connect((lambda: self.refresh_data(cmd='dtu_read')))
        self.data_load_timer.start(10)

    def refresh_data(self, cmd=None):
        # 强制更新界面
        try:
            if cmd in self.refresh_function_dict:
                app.processEvents()
                self.refresh_function_dict.get(cmd)()
        except Exception as e:
            print(e, traceback.format_exc())

    def get_dtu_data(self):
        data = self.get_data('dtu_read')
        print(data)
        print(type(data))

        # 使用get方法并提供默认值以避免KeyError
        self.set_line_edit_text(self.comboBox, data.get("mode", "- -"))
        self.set_line_edit_text(self.lineEdit, data.get("apn", "- -"))
        self.set_line_edit_text(self.lineEdit_2, data.get("apn_user", "- -"))
        self.set_line_edit_text(self.lineEdit_3, data.get("apn_password", "- -"))
        self.set_line_edit_text(self.comboBox_2, data.get("lprun", "- -"))
        self.set_line_edit_text(self.lineEdit_4, str(data.get("uartbps", "- -")))
        self.set_line_edit_text(self.lineEdit_5, str(data.get("revtime", "- -")))
        self.radioButton.setChecked(data.get("uart485", 0) != 0)

        # 检查error_info是否存在，并且是否等于dtu.SUCCESS
        error_info = data.get("error_info")
        if error_info is not None and error_info == dtu.SUCCESS:
            self.set_tool_button_connected_style()

    def save_dtu_data(self):
        """保存DTU配置"""
        print("保存DTU配置")
        check_list = [
            self.lineEdit_4,
            self.lineEdit_5
        ]
        if not self.check_input_valid(check_list):
            return
        data = {
            "mode": self.comboBox.currentText(),
            "apn": self.lineEdit.text(),
            "apn_user": self.lineEdit_2.text(),
            "apn_password": self.lineEdit_3.text(),
            "lprun": self.comboBox_2.currentText(),
            "uartbps": int(self.lineEdit_4.text()),
            "revtime": int(self.lineEdit_5.text()),
            "uart485": 1 if self.radioButton.isChecked() else 0
        }
        data = self.get_data('dtu_write', data)
        print(data)

    def get_socket_data(self):
        data = self.get_data('socket_read')
        self.set_line_edit_text(self.comboBox_3, data.get("type", "- -"))
        self.set_line_edit_text(self.lineEdit_6, data.get("host", "- -"))
        self.set_line_edit_text(self.lineEdit_7, data.get("port", "- -"))
        self.set_line_edit_text(self.lineEdit_8, data.get("heartbeat", "- -"))
        self.set_line_edit_text(self.lineEdit_17, data.get("heartbeat_time", "- -"))
        self.set_line_edit_text(self.lineEdit_9, data.get("register", "- -"))

        error_info = data.get("error_info")
        if error_info == dtu.SUCCESS:
            self.set_tool_button_connected_style()

    def save_socket_data(self):
        """保存socket配置"""
        print("保存socket配置")
        check_list = [
            self.lineEdit_7,
            self.lineEdit_17,
        ]
        if not self.check_input_valid(check_list):
            return
        data = {
            "type": self.comboBox_3.currentText(),
            "host": self.lineEdit_6.text(),
            "port": int(self.lineEdit_7.text()),
            "heartbeat": self.lineEdit_8.text(),
            "register": self.lineEdit_9.text(),
            "heartbeat_time": int(self.lineEdit_17.text()),
        }
        data = self.get_data('socket_write', data)
        print(data)

    def get_socket1_data(self):
        data = self.get_data('socket1_read')
        self.set_line_edit_text(self.comboBox_7, data.get("type", "- -"))
        self.set_line_edit_text(self.lineEdit_35, data.get("host", "- -"))
        self.set_line_edit_text(self.lineEdit_36, data.get("port", "- -"))
        self.set_line_edit_text(self.lineEdit_37, data.get("heartbeat", "- -"))
        self.set_line_edit_text(self.lineEdit_38, data.get("heartbeat_time", "- -"))
        self.set_line_edit_text(self.lineEdit_39, data.get("register", "- -"))

        error_info = data.get("error_info")
        if error_info == dtu.SUCCESS:
            self.set_tool_button_connected_style()

    def save_socket1_data(self):
        """保存socket1配置"""
        print("保存socket1配置")
        check_list = [
            self.lineEdit_36,
            self.lineEdit_38,
        ]
        if not self.check_input_valid(check_list):
            return
        data = {
            "type": self.comboBox_7.currentText(),
            "host": self.lineEdit_35.text(),
            "port": int(self.lineEdit_36.text()),
            "heartbeat": self.lineEdit_37.text(),
            "register": self.lineEdit_39.text(),
            "heartbeat_time": int(self.lineEdit_38.text()),
        }
        data = self.get_data('socket1_write', data)
        print(data)

    def get_sim_data(self):
        data = self.get_data('sim_read')
        self.set_line_edit_text(self.lineEdit_43, data.get("id", "- -"))
        self.set_line_edit_text(self.lineEdit_44, data.get("imsi", "- -"))
        self.set_line_edit_text(self.lineEdit_45, data.get("iccid", "- -"))

        error_info = data.get("error_info")
        if error_info == dtu.SUCCESS:
            self.set_tool_button_connected_style()

    def get_sys_data(self):
        data = self.get_data('sys_read')
        self.set_line_edit_text(self.lineEdit_41, data.get("version", "- -"))
        self.set_line_edit_text(self.lineEdit_42, data.get("imei", "- -"))

        error_info = data.get("error_info")
        if error_info == dtu.SUCCESS:
            self.set_tool_button_connected_style()

    def load_data(self):
        """加载真实数据并更新界面"""
        for current_index in range(self.tabWidget.count()):
            try:

                if current_index == 1:  # DTU配置标签页
                    self.get_dtu_data()
                elif current_index == 2:  # socket配置标签页
                    self.get_socket_data()

                elif current_index == 3:  # socket1配置标签页
                    self.get_socket1_data()

                elif current_index == 4:  # SIM标签页
                    self.get_sim_data()

                elif current_index == 5:  # 系统信息标签页
                    self.get_sys_data()
                # 其他页签的处理...
            except Exception as e:
                print(f"Error loading data: {e}")

    def set_line_edit_text(self, widget, text):
        """设置LineEdit或ComboBox的文本"""
        if isinstance(widget, QLineEdit):
            widget.setText(text)
        elif isinstance(widget, QComboBox):
            widget.setCurrentText(text)

    def fill_sockets(self):
        """填充socket配置标签页"""
        print("填充socket配置标签页")
        data = {
            "socket_type": LOADING,
            "host_address": LOADING,
            "port": '0',
            "heartbeat_data": LOADING,
            "heartbeat_interval": '0',
            "register_packet": LOADING,
            "timeout": LOADING
        }
        self.set_line_edit_text(self.comboBox_3, data["socket_type"])
        self.set_line_edit_text(self.lineEdit_6, data["host_address"])
        self.set_line_edit_text(self.lineEdit_7, data["port"])
        self.set_line_edit_text(self.lineEdit_8, data["heartbeat_data"])
        self.set_line_edit_text(self.lineEdit_17, data["heartbeat_interval"])
        self.set_line_edit_text(self.lineEdit_9, data["register_packet"])

        # 断开定时器已有的连接
        try:
            self.data_load_timer.timeout.disconnect()
        except TypeError:
            pass

        # 启动定时器模拟数据加载延迟
        self.data_load_timer.timeout.connect((lambda: self.refresh_data(cmd='socket_read')))
        self.data_load_timer.start()

    def fill_socket1tabs(self):
        """填充socket1配置标签页"""
        print("填充socket1配置标签页")
        data = {
            "socket_type": LOADING,
            "host_address": LOADING,
            "port": '0',
            "heartbeat_data": LOADING,
            "heartbeat_interval": '0',
            "register_packet": LOADING,
            "timeout": LOADING
        }
        self.set_line_edit_text(self.comboBox_7, data["socket_type"])
        self.set_line_edit_text(self.lineEdit_35, data["host_address"])
        self.set_line_edit_text(self.lineEdit_36, data["port"])
        self.set_line_edit_text(self.lineEdit_37, data["heartbeat_data"])
        self.set_line_edit_text(self.lineEdit_38, data["heartbeat_interval"])
        self.set_line_edit_text(self.lineEdit_39, data["register_packet"])

        # 断开定时器已有的连接
        try:
            self.data_load_timer.timeout.disconnect()
        except TypeError:
            pass
        # 启动定时器模拟数据加载延迟
        self.data_load_timer.timeout.connect((lambda: self.refresh_data(cmd='socket1_read')))
        self.data_load_timer.start()

    def fill_simtabs(self):
        """填充SIM信息标签页"""
        print("填充SIM信息标签页")
        data = {
            "id": LOADING,
            "imsi": LOADING,
            "iccid": LOADING
        }
        self.set_line_edit_text(self.lineEdit_43, data["id"])
        self.set_line_edit_text(self.lineEdit_44, data["imsi"])
        self.set_line_edit_text(self.lineEdit_45, data["iccid"])

        # 断开定时器已有的连接
        try:
            self.data_load_timer.timeout.disconnect()
        except TypeError:
            pass
        # 启动定时器模拟数据加载延迟
        self.data_load_timer.timeout.connect((lambda: self.refresh_data(cmd='sim_read')))
        self.data_load_timer.start()

    def fill_systabs(self):
        """填充系统属性标签页"""
        print("填充系统属性标签页")
        data = {
            "version_info": LOADING,
            "imei": LOADING
        }
        self.set_line_edit_text(self.lineEdit_41, data["version_info"])
        self.set_line_edit_text(self.lineEdit_42, data["imei"])
        # 断开定时器已有的连接
        try:
            self.data_load_timer.timeout.disconnect()
        except TypeError:
            pass
        # 启动定时器模拟数据加载延迟
        self.data_load_timer.timeout.connect((lambda: self.refresh_data(cmd='sys_read')))
        self.data_load_timer.start()

    def get_sleep_time(self):
        # 使用QInputDialog获取休眠时间
        sleep_time, ok = QInputDialog.getInt(self, "休眠", "请输入休眠时间（秒）:", 60, 1, 3600, 1)
        if ok:
            print(f"休眠 {sleep_time} 秒")
            res = self.get_data('sleep', sleep_time)
            print(res)
            print(type(res))
            if res.get('dtu_msg') == 'ok':
                self.toolButton.setStyleSheet(TOOL_BUTTON_DISCONNECTED_STYLE)
                self.toolButton.setText(_TRANSLATE("MainWindow", "离线"))
                QMessageBox.information(self, '提示', '休眠成功')
            elif res.get('dtu_msg') == 'Do not display repeatedly':
                return
            else:
                value = res.get('value')
                error_msg = f'休眠失败，错误信息：\n{value}'
                QMessageBox.warning(self, '警告', error_msg)

    def sleep_for(self, seconds):
        loop = QEventLoop()
        QTimer.singleShot(seconds * 1000, loop.quit)
        loop.exec_()

    def clear_action(self):
        # 显示确认对话框
        reply = QMessageBox()
        reply.setWindowTitle('确认')
        reply.setText('您确定要清除吗？')
        reply.setIcon(QMessageBox.Question)
        reply.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        reply.setDefaultButton(QMessageBox.No)

        result = reply.exec_()

        if result == QMessageBox.Yes:
            # 执行清除操作
            print("执行清除操作")
            res = self.get_data('default')
            print(res)
            print(type(res))
            if res.get('dtu_msg') == 'ok':
                self.toolButton.setStyleSheet(TOOL_BUTTON_DISCONNECTED_STYLE)
                self.toolButton.setText(_TRANSLATE("MainWindow", "离线"))
                QMessageBox.information(self, '提示', '清除成功')
            else:
                value = res.get('value')
                error_msg = f'清除失败，错误信息：\n{value}'
                QMessageBox.warning(self, '警告', error_msg)
        else:
            print("清除操作被取消")

    def shutdown_action(self):
        # 显示确认对话框
        reply = QMessageBox()
        reply.setWindowTitle('确认')
        reply.setText('您确定要关机吗？')
        reply.setIcon(QMessageBox.Question)
        reply.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        reply.setDefaultButton(QMessageBox.No)

        result = reply.exec_()

        if result == QMessageBox.Yes:
            # 执行关机操作
            print("执行关机操作")
            res = self.get_data('shutdown')
            print(res)
            if res.get('dtu_msg') == 'ok':
                self.toolButton.setStyleSheet(TOOL_BUTTON_DISCONNECTED_STYLE)
                self.toolButton.setText(_TRANSLATE("MainWindow", "离线"))
                QMessageBox.information(self, '提示', '关机成功')
            else:
                value = res.get('value')
                error_msg = f'关机失败，错误信息：\n{value}'
                QMessageBox.warning(self, '警告', error_msg)
        else:
            print("关机操作被取消")

    def restart_action(self):
        # 显示确认对话框
        reply = QMessageBox()
        reply.setWindowTitle('确认')
        reply.setText('您确定要重启吗？')
        reply.setIcon(QMessageBox.Question)
        reply.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        reply.setDefaultButton(QMessageBox.No)

        result = reply.exec_()

        if result == QMessageBox.Yes:
            # 执行重启操作
            print("执行重启操作")
            res = self.get_data('reboot')
            print(res)
            if res.get('dtu_msg') == 'ok':
                self.toolButton.setStyleSheet(TOOL_BUTTON_DISCONNECTED_STYLE)
                self.toolButton.setText(_TRANSLATE("MainWindow", "离线"))
                QMessageBox.information(self, '提示', '重启成功')
            else:
                value = res.get('value')
                error_msg = f'重启失败，错误信息：\n{value}'
                QMessageBox.warning(self, '警告', error_msg)
            # 实际上可以调用系统命令来重启
            # os.system('shutdown /r /t 0')  # Windows重启命令
        else:
            print("重启操作被取消")

    def upgrade(self):
        print("升级")
        # 弹出输入对话框
        version_info, ok = QInputDialog.getText(self, '版本信息', '请输入URL(可以为空):', QLineEdit.Normal, '')

        if ok:
            # 用户点击了确认按钮
            version_info = version_info if version_info else None
            res = self.get_data('sys_ota', version_info)
            if isinstance(res, dict):
                if res.get('dtu_msg') == 'Do not display repeatedly':
                    return
                else:
                    error_msg = f'升级失败，错误信息：\n{res}'
                    QMessageBox.warning(self, '警告', error_msg)
                    return
            res_list = res.split("DTU>")
            if len(res_list) < 3:
                error_msg = '升级指令执行异常，请查看日志!'
                QMessageBox.warning(self, '警告', error_msg)
                return
            status = json.loads(res_list[1]).get('dtu_msg')
            value = json.loads(res_list[-1]).get('value')
            print(f'res_list:{res_list},升级状态：{status}, 升级信息：{value}')
            if status == 'ok':
                massage = OTA_STATUS.get(value)
                QMessageBox.information(self, '提示', massage)
            else:
                error_msg = '升级指令执行异常，请查看日志!'
                QMessageBox.warning(self, '警告', error_msg)

        else:
            # 用户点击了取消按钮
            print("升级操作被取消")

    def display_message(self, message):
        QMessageBox.information(self, '提示', message)

    def set_ports_select(self):
        """
        设置端口选择下拉框
        :return:
        """

        for port in PORTS:
            if port.device == 'COM3':
                dtu.port = port.device
                self.comboBox_4.setItemText(0, _TRANSLATE("MainWindow", port.description))
            else:
                self.comboBox_4.addItem(port.description)
            dtu.baudrate = self.lineEdit_18.text()

    def on_combo_box_changed(self, index):
        """
        下拉框选择端口
        :param index:
        :return:
        """
        try:
            com_item_text = self.comboBox_4.currentText()
            for port in PORTS:
                if port.description == com_item_text:
                    dtu.port = port.device
                    break
            print(f"Selected option: {com_item_text}")
        except Exception as e:
            print(f"Error: {e}", traceback.format_exc())

    def on_text_changed(self, text):
        print(f"输入的内容: {text}")
        dtu.baudrate = text

    def write_to_text_browser(self, text):
        # 写入新的文本
        self.textBrowser.append(text)

    def clear_text_browser(self):
        self.textBrowser.clear()

    def get_data(self, cmd, value=None):
        try:
            command = dtu.splicing_instruction(cmd, value)
            send_text = f'{datetime.datetime.now()}-发送({dtu.port})-({dtu.baudrate}):\n {command}\n'
            self.write_to_text_browser(send_text)
            print(command)
            res = dtu.send_command(command)
            # 强制更新界面
            res_text = f'{datetime.datetime.now()}-接收:\n {res}\n'
            self.write_to_text_browser(res_text)
            app.processEvents()
            if self.display_error_value(res):
                return {'dtu_msg': 'Do not display repeatedly'}
            if '>' in res and len(res.split('>')) <= 2:
                json_response = res.split('>')[1]
                final_response = json.loads(json_response)
                # return final_response
                if cmd in dtu.PROCESS_RESPONSE_DICT:
                    processor = dtu.PROCESS_RESPONSE_DICT.get(cmd)
                    return processor(final_response)
                return final_response
            print(f'resssss:{res}')
            return res
        except Exception as e:
            print(f"Error: {e}", traceback.format_exc())
            return {}

    def display_error_value(self, response_dict):
        if isinstance(response_dict, dict) and response_dict.get('value') == '未接收到有效响应':
            error_value = response_dict.get('value')
            QMessageBox.warning(self, '警告', f'{error_value},详情请查看日志')
            return True
        return False

    def set_int_validator(self, ):
        # 创建 QIntValidator 验证器
        line_edit_list = [self.lineEdit_18, self.lineEdit_4, self.lineEdit_5, self.lineEdit_7, self.lineEdit_17,
                          self.lineEdit_36, self.lineEdit_38]
        for line_edit in line_edit_list:
            validator = QIntValidator(-2147483648, 2147483647, self)
            line_edit.setValidator(validator)

    def check_input_valid(self,check_input_list):

        for widget in check_input_list:
            if widget.text() == '':
                QMessageBox.warning(self, '警告', f'{widget.objectName()}不能为空')
                return False
            try:
                int(widget.text())
            except ValueError:
                QMessageBox.warning(self, '警告', f'请输入正确的数据')
                return False
        return True


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    window = MainWindow()
    window.set_ports_select()
    window.show()
    sys.exit(app.exec_())
